from urllib.parse import urlparse

from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.utils.translation import gettext_lazy as _

class RootHttpURLValidator:
    message = _('不是一个有效的根网址')
    schemes = ["http", "https"]

    def __call__(self, value):
        # 首先验证是否是合法 URL 格式
        try:
            URLValidator()(value)
        except ValidationError:
            raise ValidationError(self.message)

        # 判断是否为根网址，不能有路径、query参数和锚点
        if '?' in value or '#' in value:
            raise ValidationError(self.message)

        parsed = urlparse(value)
        if parsed.path not in ('', '/') or parsed.query or parsed.fragment:
            raise ValidationError(self.message)



root_http_url_validator = RootHttpURLValidator()

